<template>
  <n-card :bordered="false" class="proCard">
    <BasicTable
      title="用户列表"
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
    >
    </BasicTable>
  </n-card>
</template>
<script lang="ts">
import {defineComponent, h, reactive, ref, toRefs} from 'vue';
import {BasicTable, TableAction} from '@/components/Table';
import {columns} from './basicColumns';
import {FormInst, useDialog, useMessage} from 'naive-ui';
import {updateUserStatus, userPage} from "@/api/user";
import {MinusCircleOutlined, PlusCircleOutlined} from "@vicons/antd";

export default defineComponent({
  components: { BasicTable },
  setup() {
    // 查
    const loadDataTable = async (params) => {
      return await userPage(params).catch(e => message.error(e.message));;
    };

    const actionRef = ref();

    const formRef = ref<FormInst | null>(null)

    const state = reactive({
      params: {},
      actionColumn: {
        width: 150,
        title: '操作',
        dataIndex: 'action',
        fixed: 'right',
        align: 'center',
        render(record) {
          return h(TableAction, {
            style: 'text',
            actions: createActions(record),
          });
        },
      },
    });

    function createActions(record) {
      if (record.status == 1) {
        return [
          {
            label: '禁用',
            type: 'error',
            icon: MinusCircleOutlined,
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ];
      } else {
        return [
          {
            label: '启用',
            type: 'success',
            icon: PlusCircleOutlined,
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ];
      }
    }

    function handleEdit(record) {
      dialog.warning({
        title: '警告',
        content: '确认修改用户状态？',
        positiveText: '确认',
        negativeText: '取消',
        onPositiveClick: () => {
          updateUserStatus(record.id).then(() => {
            reloadTable();
            message.success("修改状态成功");
          }).catch(e => message.error(e.message));
        },
      })
    }

    function onCheckedRow(rowKeys) {
      console.log(rowKeys);
    }

    function reloadTable() {
      actionRef.value.reload();
    }

    const message = useMessage();
    const dialog = useDialog();

    return {
      ...toRefs(state),
      columns,
      actionRef,
      loadDataTable,
      onCheckedRow,
      reloadTable,
      formRef,
    };
  },
});
</script>
